﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.RealTime;
using Abp.Timing;
using DHJ.Cost.Authorization.Roles;
using DHJ.Cost.Authorization.Users;
using DHJ.Cost.Chat;
using Microsoft.EntityFrameworkCore;

namespace DHJ.Cost.RealTimeCost
{
    public class EstimatedCostManager : CostDomainServiceBase, IEstimatedCostManager
    {
        private readonly ICostCommunicator _costCommunicator;
        private readonly IOnlineClientManager<ChatChannel> _onlineClientManager;
        private readonly RoleManager _roleManager;
        private readonly IRepository<User, long> _userRepository;
        private readonly IRepository<EstimatedCostMessage, Guid> _estimatedCostMessagerRepository;

        public EstimatedCostManager(ICostCommunicator costCommunicator,
            IOnlineClientManager<ChatChannel> onlineClientManager, RoleManager roleManager,
            IRepository<User, long> userRepository, IRepository<EstimatedCostMessage, Guid> estimatedCostMessagerRepository)
        {
            _costCommunicator = costCommunicator;
            _onlineClientManager = onlineClientManager;
            _roleManager = roleManager;
            _userRepository = userRepository;
            _estimatedCostMessagerRepository = estimatedCostMessagerRepository;
        }

        [UnitOfWork]
        public virtual async Task SendCostMessageAsync(EstimatedCost message)
        {
            var role = await _roleManager.GetRoleByNameAsync(CostConsts.RealTimeCostRole);

            if (role == null)
            {
                return;
            }

            var users = await _userRepository.GetAll().Include(e => e.Roles)
                .Where(e => e.Roles.Any(r => r.RoleId == role.Id && r.TenantId == role.TenantId)).ToListAsync();

            // 为每个用户生成 EstimatedCostMessage

            foreach (var user in users)
            {
                var entity = new EstimatedCostMessage()
                {
                    CostId = message.Id,
                    CreationTime = Clock.Now,
                    UserId = user.Id,
                    Cost = message
                };

                await _estimatedCostMessagerRepository.InsertAsync(entity);

                await _costCommunicator.SendMessageToClient(
                    _onlineClientManager.GetAllByUserId(new UserIdentifier(user.TenantId, user.Id)),
                    entity
                );
            }
        }
    }
}